// pages/editInfo/index.js
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'
const sextypeList = [{
    sexname: '男 ♂'
  },
  {
    sexname: '女 ♀'
  },
  {
    sexname: '其他'
  }
]
Page({

  /**
   * 页面的初始数据
   */
  data: {
    avatarUrl: defaultAvatarUrl,
    nickname: '',
    school: '',
    major: '',
    wxid: '',
    connectnum: '',
    sextypeList,
    path: '',
    filename: '',
    birthdate:'',
    currentdate:''
  },
  binddateChange: function (e) {
    this.setData({
      birthdate: e.detail.value,
    })
  },
  bindPickerChange: function (e) {
    let index = e.detail.value
    this.setData({
      sextype: sextypeList[index].sexname,
    })
  },
  file: function (e) {
    wx.chooseMessageFile({
        count: 1, //能选择文件的数量
        type: 'file', //能选择文件的类型,我这里只允许上传文件.还有视频,图片,或者都可以
        success(res) {
          var size = res.tempFiles[0].size;
          var filename = res.tempFiles[0].filename;
          var newfilename = filename + "";

          if (size > 4194304 || newfilename.indexOf(".pdf") == -1) { //我还限制了文件的大小和具体文件类型
            wx.showToast({
              title: '文件大小不能超过4MB,格式必须为pdf！',
              icon: "none",
              duration: 2000,
              mask: true
            })
          } else {
            that.setData({
              path: res.tempFiles[0].path, //将文件的路径保存在页面的变量上,方便 wx.uploadFile调用
              filename: filename //渲染到wxml方便用户知道自己选择了什么文件
            })
          }
        }
      }),
      wx.uploadFile({
        url: serverUrl, //上传的路径
        filePath: that.data.path, //刚刚在data保存的文件路径
        name: 'file', //后台获取的凭据
        success() {
          wx.showToast({ //做个提示或者别的操作
            title: '',
            icon: "none",
            duration: 5000,
            mask: true,
            success: function (res) {

            }
          })
        }
      })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let userInfo = wx.getStorageSync('userInfo'),openid=wx.getStorageSync('OPENID')
    if (userInfo) {
      this.setData({
        avatarUrl: userInfo.avatar,
        nickname: userInfo.nickname,
        realname:userInfo.realname,
        sextype:userInfo.sextype,
        birthdate:userInfo.birthdate,
        school: userInfo.school,
        major: userInfo.major,
        wxid: userInfo.wxid,
        connectnum: userInfo.connectnum,
        openid: userInfo._openid,
        self_intro:userInfo.self_intro
      })
    } else {
      this.setData({
        openid: wx.getStorageSync('OPENID')
      })
      wx.cloud.database().collection('users').where({_openid:openid}).get({
        success:res=>{
          let userInfo = res.data[0]
          this.setData({
            avatarUrl: userInfo.avatar,
            nickname: userInfo.nickname,
            realname:userInfo.realname,
            sextype:userInfo.sextype,
            birthdate:userInfo.birthdate,
            school: userInfo.school,
            major: userInfo.major,
            wxid: userInfo.wxid,
            connectnum: userInfo.connectnum,
            openid: userInfo._openid,
            self_intro:userInfo.self_intro
          })
        }
      })
    }
    this.setData({
      currentdate: new Date()
    })

  },
  onChooseAvatar(e) {
    const {
      avatarUrl
    } = e.detail
    const name = Math.random() * 1000000;
    const cloudPath = "avatarUrl/" + name + avatarUrl.match(/\.[^.]+?$/)[0]
    wx.cloud.uploadFile({
      cloudPath, //云存储图片名字
      filePath: avatarUrl, //临时路径
      success: res => {
        console.log('[上传图片] 成功：', res)
        this.setData({
          avatarUrl: res.fileID,
        })
      },
      fail: e => {
        console.error('[上传图片] 失败：', e)
      },
      complete: (res) => {

      }
    });

  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },
  formSubmit: function (e) {
    let data = e.detail.value
    Object.assign(data, {
      avatar: this.data.avatarUrl,
      _openid: this.data.openid
    })
    wx.setStorageSync('userInfo', data)
    wx.cloud.init({
      env: 'cloud1-5glocnmp62950062'
    })
    wx.cloud.callFunction({
      name: 'updateUserinfo',
      data: {
        data
      },
      success: function (res) {
        wx.showToast({
          title: '上传成功！',
          duration: 2000,
          icon: 'success',
          complete: () => {
            wx.navigateBack({
              delta: 1,
            })
          }
        })
        console.log(res)
      },
      fail: function () {
        wx.showToast({
          title: '上传失败',
          icon: 'error',
        })
      },
      complete: res => {}
    })

  },
})